using CommunityToolkit.Mvvm.ComponentModel;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Data;
using System.Collections;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading;
using System.Threading.Tasks;
using Windows.Foundation;

namespace WinUITest.Pages
{
    [Menu("懒加载")]
    public sealed partial class LazyLoadingPage : Page
    {
        public LazyLoadingViewModel ViewModel { get; } = new();
        public LazyLoadingPage() => InitializeComponent();
    }
    public class LazyLoadingViewModel
    {
        public DataListViewModel DataList { get; } = [];
        public LazyLoadingViewModel()
        {
            for (int i = 0; i < 20; i++)
            {
                DataList.Add(new DataViewModel() { Name = i.ToString() });
            }
        }
    }
    public class DataListViewModel : ObservableCollection<DataViewModel>, IList, INotifyCollectionChanged, ISupportIncrementalLoading
    {
        public bool HasMoreItems => true;
        public IAsyncOperation<LoadMoreItemsResult> LoadMoreItemsAsync(uint count)
            => AsyncInfo.Run(async token => await LoadMoreItemsAsync(count, token));
        private async Task<LoadMoreItemsResult> LoadMoreItemsAsync(uint count, CancellationToken? token = null)
        {
            int nowIndex = Count;
            uint trueCount = 0;
            for (int i = 0; i < count; i++)
            {
                if (token is not null && token.Value.IsCancellationRequested) break;
                Add(new DataViewModel() { Name = (nowIndex + i).ToString() });
                trueCount += 1;
            }
            await Task.CompletedTask;
            return new LoadMoreItemsResult(trueCount);
        }
    }
    public partial class DataViewModel : ObservableObject
    {
        [ObservableProperty]
        public partial string Name { get; set; } = string.Empty;
    }
}
